/**
 * encryption.js
 * 加密方式
 * crypto-js文档：https://cryptojs.gitbook.io/docs/ 更多加密方式看文档
 * crypto-js示例：https://tool.oschina.net/encrypt
 * @author HLonlin <1021944439@qq.com>
 */
import CryptoJS from 'crypto-js'

// 加密密码 ${key} 长度不足16位补全处理
const fillkey = key => {
  const filledkey = Buffer.alloc(128 / 8)
  const keys = Buffer.from(key)
  if (keys.length < filledkey.length) {
    filledkey.map((b, i) => (filledkey[i] = keys[i]))
  }
  return filledkey
}

// AES加密
export const encryptAES = (content, key) => {
  const keys = CryptoJS.enc.Utf8.parse(fillkey(key))
  return CryptoJS.AES.encrypt(content, keys, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  }).toString()
}
// AES解密
export const decryptAES = (content, key) => {
  const keys = CryptoJS.enc.Utf8.parse(fillkey(key))
  return CryptoJS.AES.decrypt(content, keys, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  }).toString(CryptoJS.enc.Utf8)
}